#include "groupBy.h"

GroupBy::~GroupBy()
{
    if(columnReferences != NULL){
        for(unsigned int i=0; i<columnReferences->size(); i++) delete columnReferences->at(i);
        delete columnReferences; columnReferences = NULL;
    }// if
}

GroupBy::GroupBy(const GroupBy& other)
{
    if(other.columnReferences == NULL) this->columnReferences = NULL;
    else{
        columnReferences = new vector<ColumnReference *>();
        for(unsigned int i=0; i<other.columnReferences->size(); i++) {
            ColumnReference * c = dynamic_cast <ColumnReference*> (other.columnReferences->at(i)->clone());
            columnReferences->push_back(c);
        }// for
    }// if-else
}

GroupBy::GroupBy(vector<ColumnReference *> * columnReferences)
{
    if(columnReferences == NULL) this->columnReferences = NULL;
    else{
        this->columnReferences = new vector<ColumnReference *>();
        for(unsigned int i=0; i<columnReferences->size(); i++) {
            ColumnReference * c = dynamic_cast <ColumnReference*> (columnReferences->at(i)->clone());
            this->columnReferences->push_back(c);
        }// for
    }// if-else
}

int GroupBy::size()
{
    return columnReferences->size();
}

void GroupBy::addColumnReference(ColumnReference * columnRef)
{
    if(columnReferences == NULL) columnReferences = new vector<ColumnReference *>();
    if(columnRef != NULL) columnReferences->push_back(dynamic_cast <ColumnReference*> (columnRef->clone()));
}

void GroupBy::addColumnReference(const string & table, const string & column)
{
    if(columnReferences == NULL) columnReferences = new vector<ColumnReference *>();
    ColumnReference * c = new ColumnReference(table,column);
    columnReferences->push_back(c);
}

vector<ColumnReference *> * GroupBy::getColumnReferences() //const
{
    return columnReferences;
}

string GroupBy::toString()
{
    string str = "<";
    if(columnReferences != NULL){
        for(unsigned int i=0; i<columnReferences->size(); i++){
            str = str + columnReferences->at(i)->toString() + ",";
        }//for
        str.erase(str.length()-1);
    }// if
    str = str + ">";
    return str;
}

void GroupBy::setColumnReferences(vector<ColumnReference *> * columnReferences)
{
    for(unsigned int i=0; i<this->columnReferences->size(); i++) delete this->columnReferences->at(i);
    delete this->columnReferences; this->columnReferences = NULL;

    if(columnReferences == NULL) this->columnReferences = NULL;
    else{
        this->columnReferences = new vector<ColumnReference *>();
        for(unsigned int i=0; i<columnReferences->size(); i++) {
            ColumnReference * c =  dynamic_cast <ColumnReference*> (columnReferences->at(i)->clone());
            this->columnReferences->push_back(c);
        }// for
    }// if-else
}

GroupBy * GroupBy::clone()
{
    return new GroupBy(*this);
}

